#include <iostream>
#include <sys/socket.h> // socket
#include <netinet/in.h> // local
#include <arpa/inet.h> // htons inet_addr
#include <cstring> // memset 
#include <unistd.h> // close

// ./TestUDPClient serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Please Use:./TestUDPClient serverip serverport" << std::endl;
        return 1;
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cout << "socket fail" << std::endl;
        exit(1);
    }

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    while (true)
    {
        std::string inbuffer;
        std::cout << "Please Enter# ";
        std::getline(std::cin, inbuffer);

        ssize_t n = sendto(sockfd, inbuffer.c_str(), inbuffer.size(), 0, (struct sockaddr*)&server, sizeof(server));
        if (n > 0)
        {
            char buffer[1024];
            struct sockaddr_in tmp;
            socklen_t len = sizeof(tmp); // 需要初始化
            ssize_t m = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&tmp, &len);
            if (m > 0)
            {
                buffer[m] = 0;
                std::cout << "Server echo# " << buffer << std::endl;
            }
            else
            {
                std::cout << "recvfrom fail" << std::endl;
                break;
            }
        }
        else
        {
            std::cout << "sendto fail" << std::endl;
            break;
        }
    }

    close(sockfd);

    return 0;
}